#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""NM64 station read input data

Copyright (C) 2011-2014 Christian T. Steigies <steigies@physik.uni-kiel.de>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

__author__ = "Christian T. Steigies <steigies@physik.uni-kiel.de>"
__license__ = "GPL License"

## --------------------------------------------------------------------------

#import os
import sys
from datetime import datetime, timedelta

from nmdb.tools.datetool import valid_date
from nmdb.station.bartol import bartol_station
from nmdb.station.kiel import kiel_station
from nmdb.station.kiel2 import kiel2_station
from nmdb.station.mexico import mexico_station
from nmdb.station.australia import australia_station
from nmdb.station.tibet import tibet_station
from nmdb.station.south_africa import south_africa_station
from nmdb.station.new_hampshire import new_hampshire_station
from nmdb.station.calgary import calgary_station
from nmdb.station.mininm import mininm_station
from nmdb.station.wdc import wdc_station
from nmdb.station.dourbes import dourbes_station

valid_station = bartol_station + kiel_station + kiel2_station + mexico_station + australia_station + tibet_station \
    + south_africa_station + new_hampshire_station + calgary_station + mininm_station + wdc_station + dourbes_station

#__all__ = ["", ""]


"""
TODO read_year, read_month, read_day from australia with function as argument? convert to class and object!

STATION.py to provide read_rt (realtime) and read_rev (revised) functions
with arguments (options, station, data_type, year, month, day)

 check if station is valid for this function
 return list of values in NMDB format for one day/month/year
 data_type: 1m, 1h, env, meta

"""

## --------------------------------------------------------------------------
def read_revised(station, data_type, options):
    """read revised data for station name (for use with station2sql)
    specify year, month, or day with options
    """

    default_year = 2015  # TODO find a better method for selecting the default year
    try:  # year needs to be defined
        year = options.year
        if year is None:
            year = default_year
    except AttributeError:
        year = default_year
    try:
        month = options.month
    except AttributeError:
        month = None  # read all months
    try:
        day = options.day
    except AttributeError:
        day = None  # read all days

    if station in australia_station:
        from nmdb.station.australia import read_rev
    elif station in bartol_station:
        from nmdb.station.bartol import read_rev
    elif station in calgary_station:
        from nmdb.station.calgary import read_rev
    elif station in dourbes_station:
        from nmdb.station.dourbes import read_rev
    elif station in kiel_station:
        from nmdb.station.kiel import read_rev
    elif station in kiel2_station:
        from nmdb.station.kiel2 import read_rev
    elif station in mexico_station:
        from nmdb.station.mexico import read_rev
    elif station in mininm_station:
        from nmdb.station.mininm import read_rev
    elif station in new_hampshire_station:
        from nmdb.station.new_hampshire import read_rev
    elif station in south_africa_station:
        from nmdb.station.south_africa import read_rev
    elif station in tibet_station:
        from nmdb.station.tibet import read_rev
    elif station in wdc_station:
        from nmdb.station.wdc import read_rev
    else:
        print "undefined station:", station, "|", valid_station
        sys.exit(0)

    value = []
    if month is None:
        for i in range(1, 13):  # read all months
            for j in range(1, 32):  # read all days
                if valid_date(year, i, j):
                    data = read_rev(options, station, data_type, year, i, j)
                    if data != None:
                        value += data
    elif day is None:
        for i in range(1, 32):  # read all days
            if valid_date(year, month, i):
                data = read_rev(options, station, data_type, year, month, i)
                if data != None:
                    value += data
    else:
        if valid_date(year, month, day):
            value = read_rev(options, station, data_type, year, month, day)

    if options.verbose:
        print "Read revised data for station", station.upper()

    return value


## --------------------------------------------------------------------------
def read_realtime(station, data_type, options, year, month, day):
    """
    read real-time data for station for a given day (for use with upload)
    TODO: all read_station functions use identical parameters. specify "ori" or "rev" as australia
    """

    if station in australia_station:
        from nmdb.station.australia import read_rt
    elif station in bartol_station:
        from nmdb.station.bartol import read_rt
    elif station in calgary_station:
        from nmdb.station.calgary import read_rt
    elif station in dourbes_station:
        from nmdb.station.dourbes import read_rt
    elif station in kiel_station:
        from nmdb.station.kiel import read_rt
    elif station in kiel2_station:
        from nmdb.station.kiel2 import read_rt
    elif station in mexico_station:
        from nmdb.station.mexico import read_rt
    elif station in mininm_station:
        from nmdb.station.mininm import read_rt
    elif station in new_hampshire_station:
        from nmdb.station.new_hampshire import read_rt
    elif station in south_africa_station:
        from nmdb.station.south_africa import read_rt
    elif station in tibet_station:
        from nmdb.station.tibet import read_rt
    elif station in wdc_station:
        from nmdb.station.wdc import read_rt
    else:
        print "No import filter for %s available" % (station)
        raise ValueError  # station not defined

    data = read_rt(options, station, data_type, year, month, day)

    if options.verbose:
        print "Read ori/real-time data for station", station.upper()

    return data


## --------------------------------------------------------------------------
def data_realtime(station, data_type, options, this_day, nmdb_time, days_max):
    """
    read readtime data
    station: name of the station
    mode: read ori or 1h data
    this_day: start reading with this_day
    days_max: read data only for this many days (minimum must be 2)
    """

    value = []
    days_read = 0
    if days_max < 2:
        days_max = 2
    this_day = datetime(this_day.year, this_day.month, this_day.day, 0, 0, 0)
    while True: #len(data) == 0:
        if this_day > nmdb_time:  # no more data available.
            break
        if options.verbose > 0:
            print "reading", this_day.year, this_day.month, this_day.day
        data = read_realtime(station, data_type, options, this_day.year, this_day.month, this_day.day)

        if data is None:      # no data
            pass
        elif len(data) == 0:  # no data?
            pass
        else:
            value += data
            days_read += 1
            if days_read >= days_max:
                break

        this_day += timedelta(days=1)

    return value


## --------------------------------------------------------------------------
if __name__ == "__main__":
    print "This is the NMDB station read module."

    from nmdb.tools.configtool import parse_options
    (options, args) = parse_options("upload")
    if options.verbose > 1:
        print "options:", options
        print "args:", args
    if options.dryrun:
        print "dryrun: not sending any data to NMDB"
    rcfile = options.rcfile

    station = "drbs"
    #data_type="1h"
    data_type="1m"
    year = 2014
    month = 10
    day = 10
#    data = read_rt(options, station, data_type, year, month, day)
    data = read_realtime(station, data_type, options, year, month, day)
    for line in data:
        print line

    options.year = 2014
    options.month = month
    options.day = day
    data = read_revised(station, data_type, options)
    for line in data:
        print line
